package com.chen.librarysystem.log;

import com.chen.librarysystem.context.Constant;
import com.chen.util.LocalDateTimeUtil;

import java.io.IOException;
import java.util.logging.*;

public class LibraryLog {
    private static final Logger logger = Logger.getLogger(LibraryLog.class.getName());

    static {
        try {
            logger.setUseParentHandlers(false);
            logger.setLevel(Level.ALL);

            FileHandler fileHandler = new FileHandler(Constant.FILE_PATH + "library.log", true);
            fileHandler.setLevel(Level.ALL);
            fileHandler.setFormatter(new Formatter() {
                @Override
                public String format(LogRecord record) {
                    String timestamp = LocalDateTimeUtil.getDateTime();
                    String level = record.getLevel().getName();
                    String className = record.getSourceClassName();
                    String methodName = record.getSourceMethodName();
                    String message = record.getMessage();
                    return String.format("[%s] [%s] [%s.%s] %s%n", timestamp, level, className, methodName, message);
                }
            });
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            throw new RuntimeException("Log收集器创建失败！");
        }
    }

    public static void log(Level level, String message) {
        logger.log(level, message);
    }
}
